import classNames from 'classnames'
import stayles from './avatar.module.scss'
import { targetUrl } from '@/utils/config'
import { useEffect, useRef, useState } from 'react'
import { Upload, Button, message } from 'antd'
import type { GetProp, UploadFile, UploadProps } from 'antd'
import ImgCrop from 'antd-img-crop'
import { upload, getInfo } from '@/api/user'
import { useDispatch } from 'react-redux'

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0]

const Avatar = () => {
  /**
   * 变量集合
   */
  const userInfostr = localStorage.getItem('userInfo') || ''
  const userInfo = JSON.parse(userInfostr)
  const [isloading, setIsLoading] = useState(false)
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [isShowBtn, setIsShowBtn] = useState(false)
  const [messageApi, contextHolder] = message.useMessage()
  const dispatch = useDispatch()

  /**
   * 展示 隐藏 确定按钮
   */
  useEffect(() => {
    if (fileList.length > 0) {
      return setIsShowBtn(true)
    }
    setIsShowBtn(false)
  }, [fileList])

  /**
   *  上传图片相关操作
   */
  const onChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList)
  }
  const onPreview = async (file: UploadFile) => {
    let src = file.url as string
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader()
        reader.readAsDataURL(file.originFileObj as FileType)
        reader.onload = () => resolve(reader.result as string)
      })
    }
    const image = new Image()
    image.src = src
    const imgWindow = window.open(src)
    imgWindow?.document.write(image.outerHTML)
  }
  const beforeUpload = () => {
    return false
  }

  /**
   * 确认
   */
  const uploadRef = useRef()
  const confirm = async () => {
    try {
      console.log(fileList)
      const formData = new FormData()
      formData.append('avatar', fileList[0].originFileObj as FileType)

      setIsLoading(true)
      const res = await upload(formData, userInfo?.id)
      if (res.code < 200 || res.code > 399) {
        return messageApi.open({
          duration: 5,
          type: 'error',
          content: '头像上传失败'
        })
      }
      messageApi.open({
        type: 'success',
        content: '头像上传成功'
      })
      const user = await getInfo()
      dispatch({ type: 'setUserInfo', val: user.data })
      location.reload()
    } catch (error) {
      console.log('头像上传失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <>
      {contextHolder}
      {/* // className={classNames(stayles.box_avatar)} */}
      <div className={classNames(stayles.box_avatar)}>
        <img src={`${targetUrl}/${userInfo?.avatar}`} alt="" className={classNames(stayles.avatar)} />
        {/*  */}
        <div>上传新头像:</div>
        <ImgCrop rotationSlider>
          {/* beforeUpload={beforeUpload} */}
          {/* action={`${targetUrl}/api/v1/user/upload/${userInfo?.id}`} */}
          <Upload
            ref={uploadRef}
            action={`${targetUrl}/api/v1/user/upload/${userInfo?.id}`}
            name="avatar"
            listType="picture-card"
            fileList={fileList}
            onChange={onChange}
            onPreview={onPreview}
            beforeUpload={beforeUpload}
            maxCount={1}
          >
            + Upload
          </Upload>
        </ImgCrop>
        {isShowBtn && (
          <Button type="primary" loading={isloading} onClick={() => confirm()}>
            确定上传
          </Button>
        )}
      </div>
    </>
  )
}

export default Avatar
